import 'package:cbec_app/components/base/base_chekbox.dart';
import 'package:cbec_app/components/base/base_image.dart';
import 'package:cbec_app/components/base/base_interactive.dart';
import 'package:cbec_app/components/base/base_page.dart';
import 'package:cbec_app/components/common/common_style.dart';
import 'package:cbec_app/components/base/base_nav_bar.dart';
import 'package:cbec_app/pages/my/controller/user_auth_ctr.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:wechat_camera_picker/wechat_camera_picker.dart';

//实名认证页面
class UserAuth extends GetView<UserAuthController> {
  UserAuth({super.key});

  TextStyle tipStyle = TextStyle(fontSize: 13, color: Tools.fromHex("#AAAAAA"));
  TextStyle tipStyle2 = TextStyle(fontSize: 13, color: Tools.fromHex("#333333"));
  @override
  Widget build(BuildContext context) {
    return GetBuilder<UserAuthController>(builder: (controller) {
      return BasePage(
        title: controller.pageTitle,
        iconType: IconType.back,
        bodyColor: Colors.white,
        children: [
          Container(
            padding: EdgeInsets.only(left: 20.w, right: 20.w),
            child: SingleChildScrollView(
              child: Column(
                children: [
                  Text("根据海关要求，海外商品入境需要提交收件人身份证信息用于清关申报，请确保 提供真实有效的身份证件信息。", style: TextStyle(fontSize: 13, color: Tools.fromHex("#F83F2D"))),
                  Container(
                    padding: EdgeInsets.fromLTRB(20.w, 0.w, 20.w, 20.w),
                    child: Column(
                      children: [
                        //------表单--------------
                        Container(
                          decoration: bottom_gary_border,
                          child: Row(
                            children: [
                              Text(
                                "购买者姓名",
                                style: blackFont(14),
                              ),
                              SizedBox(width: 20.w),
                              Container(
                                padding: EdgeInsets.only(top: 15.w, bottom: 15.w),
                                width: 200.w,
                                child: TextFormField(
                                  controller: controller.nameTxtCtr,
                                  decoration: descript("请输入购买者姓名"),
                                ),
                              )
                            ],
                          ),
                        ),
                        Container(
                          decoration: bottom_gary_border,
                          child: Row(
                            children: [
                              Text(
                                "身份证号码",
                                style: blackFont(14),
                              ),
                              SizedBox(width: 20.w),
                              Container(
                                padding: EdgeInsets.only(top: 15.w, bottom: 15.w),
                                width: 200.w,
                                child: TextFormField(
                                  controller: controller.idcardTxtCtr,
                                  decoration: descript("请输入购买者身份证号码"),
                                ),
                              )
                            ],
                          ),
                        ),
                        Container(
                          decoration: bottom_gary_border,
                          child: Row(
                            children: [
                              Text(
                                "性别",
                                style: blackFont(14),
                              ),
                              SizedBox(width: 60.w),
                              Container(
                                padding: EdgeInsets.only(top: 15.w, bottom: 15.w),
                                width: 200.w,
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  children: [
                                    Text("男"),
                                    Radio(
                                      visualDensity: const VisualDensity(horizontal: -4, vertical: -4),
                                      value: 0,
                                      groupValue: controller.sexSelected,
                                      onChanged: (value) {
                                        controller.sexSelected = value!;
                                        controller.update();
                                      },
                                      activeColor: Tools.fromHex("#D81E06"),
                                    ),
                                    SizedBox(width: 20.w),
                                    Text("女"),
                                    Radio(
                                      visualDensity: const VisualDensity(horizontal: -4, vertical: -4),
                                      value: 1,
                                      groupValue: controller.sexSelected,
                                      onChanged: (value) {
                                        controller.sexSelected = value!;
                                        controller.update();
                                      },
                                      activeColor: Tools.fromHex("#D81E06"),
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                  if (controller.idcardFront == null) ...[
                    if (controller.idcardFrontUrl.isNotEmpty) ...[
                      Container(
                        padding: EdgeInsets.only(top: 30.w, bottom: 30.w),
                        alignment: Alignment.center,
                        child: ShowImageBox(image: controller.idcardFrontUrl, index: 0),
                      ),
                    ] else ...[
                      uploadBox(0, "上传人像面", context),
                    ],
                  ] else ...[
                    Container(
                      padding: EdgeInsets.only(top: 30.w, bottom: 30.w),
                      alignment: Alignment.center,
                      child: ShowImageBox(image: controller.idcardFront!, index: 0),
                    ),
                  ],
                ],
              ),
            ),
          ),

          Container(height: 10.h, color: Tools.fromHex("#FAFAFA")),
          if (controller.idcardOpposite == null) ...[
            if (controller.idcardOppositeUrl.isNotEmpty) ...[
              Container(
                padding: EdgeInsets.only(top: 30.w, bottom: 30.w),
                alignment: Alignment.center,
                child: ShowImageBox(image: controller.idcardOppositeUrl, index: 1),
              ),
            ] else ...[
              uploadBox(1, "上传国徽面", context),
            ],
          ] else ...[
            Container(
              padding: EdgeInsets.only(top: 30.w, bottom: 30.w),
              alignment: Alignment.center,
              child: ShowImageBox(image: controller.idcardOpposite!, index: 1),
            ),
          ],

          Container(color: Tools.fromHex("#FAFAFA"), height: 10.h),
          //---示例图---
          Container(
            padding: EdgeInsets.only(left: 20.w, right: 20.w),
            child: Text("示例图:"),
          ),
          Container(
            padding: EdgeInsets.only(top: 14.w, left: 20.w, right: 20.w),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                BaseImage(url: "idcard_a.png", width: 88, height: 60),
                BaseImage(url: "idcard_b.png", width: 88, height: 60),
              ],
            ),
          ),
          //---Tips
          Container(
              padding: EdgeInsets.fromLTRB(20.w, 34.w, 20.w, 6.w),
              child: RichText(
                text: TextSpan(
                  children: <TextSpan>[
                    TextSpan(
                      text: 'Tips:\n',
                      style: tipStyle,
                    ),
                    TextSpan(
                      text: '1.请按照图示要求、区分正反面上传;\n',
                      style: tipStyle,
                    ),
                    TextSpan(
                      text: '2.请使用JPG、JPEG、png格式图片进行上传,建议图片大\n',
                      style: tipStyle,
                    ),
                    TextSpan(
                      text: '小不超过2M;',
                      style: tipStyle,
                    ),
                  ],
                ),
              )),

          //描述--------------------
          Container(
            padding: EdgeInsets.only(left: 20.w, right: 20.w),
            child: RichText(text: TextSpan(children: <TextSpan>[TextSpan(text: "1)依据中国海关法律法规，购买跨境商品需要您上传身份证信息用于商品入境申报。\n", style: tipStyle2), TextSpan(text: " 2) 请确保与付款账号一致的实名信息。3) 声明:我们将妥善、安全地 (采取加密、限权、水印等措施) 储存您上传填写的身份信息，并仅用于每当您购买海外商品时，根据您授权提供给予您进行交易的商家用于所购商品的清关申报。", style: tipStyle2)])),
          ),
          //同意协议-----
          authBox(),
          //---按钮--
          solidButton("保存", () {
            controller.submit();
          }, margin: EdgeInsets.all(20.w), radius: 10),
          SizedBox(height: 20.w)
        ],
      );
    });
  }

  //图片上传框
  Widget uploadBox(int type, String text, BuildContext context) {
    return BaseInteractive(
      onClick: () {
        showModalBottomSheet(
          backgroundColor: Colors.transparent,
          context: context,
          builder: (BuildContext context) {
            return Container(
              padding: EdgeInsets.only(left: 8.w, right: 8.w),
              height: 180.h,
              child: Column(
                children: <Widget>[
                  BaseInteractive(
                      onClick: () async {
                        //拍照
                        final AssetEntity? entity = await CameraPicker.pickFromCamera(context);
                        type == 0 ? controller.idcardFront = entity : controller.idcardOpposite = entity;
                        controller.update();
                        Get.back();
                      },
                      childWidget: Container(
                          decoration: const BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.only(
                                topLeft: Radius.circular(20.0),
                                topRight: Radius.circular(20.0),
                              )),
                          alignment: Alignment.center,
                          width: double.infinity,
                          height: 50.h,
                          child: Text("拍照", style: TextStyle(fontSize: 15, fontWeight: FontWeight.w700, color: Tools.fromHex("#4D87FF"))))),
                  BaseInteractive(
                      onClick: () async {
                        var imageList = await AssetPicker.pickAssets(context, pickerConfig: AssetPickerConfig(maxAssets: 1));
                        if (type == 0) {
                          controller.idcardFront = imageList?.first;
                        } else {
                          controller.idcardOpposite = imageList?.first;
                        }
                        controller.update();
                        Get.back();
                      },
                      childWidget: Container(
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: const BorderRadius.only(
                              bottomLeft: Radius.circular(20.0),
                              bottomRight: Radius.circular(20.0),
                            ),
                            border: Border(
                              top: BorderSide(
                                color: Tools.fromHex("#D7D7D7"),
                                width: 1.0,
                              ),
                            ),
                          ),
                          alignment: Alignment.center,
                          width: double.infinity,
                          height: 50.h,
                          child: Text("从相册选择", style: TextStyle(fontSize: 15, fontWeight: FontWeight.w700, color: Tools.fromHex("#4D87FF"))))),
                  BaseInteractive(onClick: () => {Get.back()}, childWidget: Container(decoration: border_radis(Colors.white, radiusValue: 20), margin: EdgeInsets.only(top: 10.w), alignment: Alignment.center, width: double.infinity, height: 50.h, child: Text("取消", style: TextStyle(fontSize: 15, fontWeight: FontWeight.w700, color: Tools.fromHex("#4D87FF"))))),
                ],
              ),
            );
          },
        );
      },
      childWidget: Container(
        height: 160.h,
        alignment: Alignment.center,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            BaseImage(url: "camera.png", width: 44, height: 44),
            SizedBox(
              width: 20.w,
            ),
            Text(text)
          ],
        ),
      ),
    );
  }

  //同意协议组件
  Widget authBox() {
    return Container(
      width: 10.w,
      height: 30.h,
      margin: EdgeInsets.only(top: 20.w, right: 20.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(width: 18.w),
          BaseCheckBox(
            value: controller.isAgree,
            onChange: (selected) {
              print(selected);
              controller.isAgree = selected;
            },
          ),
          SizedBox(width: 5.w),
          SizedBox(
              child: Text(
            "确认授权与本人进行交易的商家使用该身份证件信息办理\n清关申报",
            softWrap: true,
            overflow: TextOverflow.ellipsis,
            maxLines: 3,
            style: TextStyle(fontSize: 11, fontWeight: FontWeight.w400, color: Tools.fromHex("#AAAAAA")),
          ))
        ],
      ),
    );
  }
}

class ShowImageBox extends StatelessWidget {
  final dynamic image;
  final int index;
  final UserAuthController controller = Get.find<UserAuthController>();

  ShowImageBox({
    super.key,
    required this.image,
    required this.index,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(top: 10.w),
      child: Stack(
        children: [
          Positioned(
            child: Container(
              clipBehavior: Clip.hardEdge,
              decoration: border_radis(Colors.white),
              child: _buildImageWidget(), // 通过 _buildImageWidget 加载图片
            ),
          ),
          Positioned(
            top: 0,
            right: 0,
            child: BaseInteractive(
              onClick: () {
                print('index ===  $index');
                if (index == 0) {
                  controller.idcardFront = null;
                  controller.idcardFrontUrl = '';
                } else {
                  controller.idcardOpposite = null;
                  controller.idcardOppositeUrl = '';
                }
                controller.update();
              },
              childWidget: Container(
                padding: const EdgeInsets.all(4), // 边框的间距
                decoration: BoxDecoration(
                  color: Colors.white, // 圆形背景色
                  shape: BoxShape.circle, // 圆形
                  border: Border.all(
                    color: Colors.black, // 边框颜色
                    width: 1, // 边框宽度
                  ),
                ),
                child: const Icon(
                  Icons.close, // 或者使用任何其他图标
                  color: Colors.black, // 图标颜色
                  size: 16,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 根据 image 类型决定加载哪种类型的图片
  Widget _buildImageWidget() {
    if (image is String) {
      // 如果 image 是 String 类型，使用 Image.network 来加载图片
      return Image.network(
        image,
        width: 170.w,
        height: 100.h,
        fit: BoxFit.cover,
      );
    } else if (image is AssetEntity) {
      // 如果 image 是 AssetEntity 类型，使用 AssetEntityImage 来加载图片
      return AssetEntityImage(
        image,
        width: 170.w,
        height: 100.h,
        isOriginal: false,
        fit: BoxFit.cover,
      );
    } else {
      // 如果 image 类型不是 String 或 AssetEntity，返回一个占位图
      return Container(
        width: 170.w,
        height: 100.h,
        color: Colors.grey[300],
        child: Icon(
          Icons.image,
          color: Colors.grey[500],
        ),
      );
    }
  }
}
